package com.starbaba.system.attach.view;

import java.io.IOException;
import java.io.Serializable;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;

import com.opensymphony.xwork2.Action;
import com.starbaba.core.hibernate.DAOFactory;
import com.starbaba.core.hibernate.HibernateDAO;
import com.starbaba.core.hibernate.Strategy;
import com.starbaba.core.utils.PkUtils;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.core.web.struts2.ExtJsonResult;
import com.starbaba.core.web.struts2.JsonResult;
import com.starbaba.system.attach.dao.DeleteAttachStrategy;
import com.starbaba.system.attach.model.AttachVO;
//import com.mtech.fdfs.FdfsManager;

@SuppressWarnings("serial")
public class AttachAction extends BaseAction{
	
	public AttachAction() {
		this.voClass = AttachVO.class;
        this.pkNameArray = new String[] { "attid" };
	}
	
	/**
	 * 删除附件操作
	 * @throws IOException
	 */
	public void deleteAttach() throws IOException{
		try{
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			AttachData targetAttach = new AttachData();
			this.setParamsMapToTargetObject(paramsMap, targetAttach);
			
			if(!targetAttach.isValid()){
				JsonResult result = new JsonResult(Action.ERROR, "参数无效");
				this.sendJsonMessage(result.getJsonString());
				return;
			}
			
			this.voClass = Class.forName(targetAttach.getVoName());
			this.pkNameArray = targetAttach.getPkCol().split("\\|");
			Serializable pk = PkUtils.getPkVO(voClass, pkNameArray, targetAttach.getPkValue());
			Object entityVO = this.getService().doFindByPk(voClass, pk);
			String attIds = BeanUtils.getProperty(entityVO, targetAttach.getAttCol());
			
			boolean findAtt = false;
			StringBuffer newAttIds = new StringBuffer();
			if(StringUtils.isNotBlank(attIds)){
				String []attaArray = attIds.split(",");
				for(String attachId : attaArray){
					if (targetAttach.getAttId().equals(attachId.trim())) {
						findAtt = true;
					} else {
						newAttIds.append(attachId.trim()).append(",");
					}
				}
				if(newAttIds.length() > 1){
					newAttIds.delete(newAttIds.length() - 1, newAttIds.length());
				}
			}
			//附件存在
			if (findAtt) {
				/* 重新设置实体附件信息  */
				BeanUtils.setProperty(entityVO, targetAttach.getAttCol(), newAttIds.toString());
				
				DeleteAttachStrategy delStrategy = new DeleteAttachStrategy(voClass, entityVO, targetAttach.getAttId());
				this.getService().doProcess(delStrategy);
			}else{
				JsonResult result = new JsonResult(Action.ERROR, "附件不存在");
				this.sendJsonMessage(result.getJsonString());
				return;
			}
		} catch (Exception ex){
			ex.printStackTrace();
			this.addErrorMessage(ex.getMessage());
			JsonResult result = new JsonResult(Action.ERROR, ex.getMessage());
			this.sendJsonMessage(result.getJsonString());
		}
		JsonResult result = new JsonResult(Action.SUCCESS);
		this.sendJsonMessage(result.getJsonString());
	}
	
	/**
	 * 删除附件操作
	 *
	 * @Copyright: Copyright (c) 2006
	 * @Company: Revenco Tech Ltd.
	 * @anthor chenminhui<chenminhui@revenco.com>
	 * @since 2014-11-7 下午02:16:07
	 * @version V1.0
	 */
	public void ajaxDeleteFile() {
		String errmsg = null;
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		try {
			final String []pkValues = getParamValueByParamsMap(paramsMap, "PK");
			getService().doProcess(new Strategy() {

				@Override
				public Object process() throws Exception {
					if(ArrayUtils.isNotEmpty(pkValues)) {
						HibernateDAO attachDAO = DAOFactory.getInstance().createHibernateDAO(AttachVO.class);
						for(String pk: pkValues) {
							AttachVO aVO = (AttachVO) attachDAO.findByPK(Long.valueOf(pk));
							if(aVO != null) {
								String savepath = aVO.getSavepath();
								//1. 删除附件信息
								attachDAO.deleteByVO(aVO);
								
								log.info("准备在FastDFS删除远程文件[" + savepath + "]...");
								//3. 删除FastDFS里面的文件
//								FdfsManager.deleteFile(savepath);
								log.info("在FastDFS成功删除远程文件[" + savepath + "]");
							}
							
						}
					}
					return null;
				}});
		} catch (Exception e) {
			errmsg = "删除附件失败，异常原因：" + e.getMessage();
			log.error(errmsg, e);
		}
		
		try {
			if(errmsg == null) {
				sendJsonMessage(new JsonResult(SUCCESS, "删除成功"));
			} else {
				sendJsonMessage(new JsonResult(ERROR, errmsg));
			}
		} catch (IOException e) {
			log.error(e, e);
		}
	}
	
	/**
	 * 上传附件操作
	 * @throws IOException
	 */
	public void uploadAttach()  throws IOException{
		try{
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			AttachData targetAttach = new AttachData();
			this.setParamsMapToTargetObject(paramsMap, targetAttach);
			
			if(!targetAttach.isValid()){
				JsonResult result = new JsonResult(Action.ERROR, "参数无效");
				this.sendJsonMessage(result.getJsonString());
				return;
			}
			this.voClass = Class.forName(targetAttach.getVoName());
			this.pkNameArray = targetAttach.getPkCol().split("\\|");
			Serializable pk = PkUtils.getPkVO(voClass, pkNameArray, targetAttach.getPkValue());
			Object entityVO = this.getService().doFindByPk(voClass, pk);
			String orgAttIds = BeanUtils.getProperty(entityVO, targetAttach.getAttCol());
			/* 附件以逗号分隔 */
			if(StringUtils.isNotBlank(orgAttIds)){
				if(orgAttIds.indexOf(targetAttach.getAttId()) < 0){
					orgAttIds = orgAttIds + "," + targetAttach.getAttId();
				}
			}else{
				orgAttIds = targetAttach.getAttId();
			}
			BeanUtils.setProperty(entityVO, targetAttach.getAttCol(), orgAttIds);
			this.getService().doUpdate(voClass, entityVO);
		} catch (Exception ex){
			ex.printStackTrace();
			this.addErrorMessage(ex.getMessage());
			JsonResult result = new JsonResult(Action.ERROR, ex.getMessage());
			this.sendJsonMessage(result.getJsonString());
		}
		JsonResult result = new JsonResult(Action.SUCCESS);
		this.sendJsonMessage(result.getJsonString());
	}
	
	/**
	 * 获取附件信息
	 * 
	 * @return
	 *
	 * @Copyright: Copyright (c) 2006
	 * @Company: Revenco Tech Ltd.
	 * @anthor chenminhui<chenminhui@revenco.com>
	 * @since 2014-11-8 下午05:27:20
	 * @version V1.0
	 */
	public String ajaxGetAttach() {
		ExtJsonResult<AttachVO> result = new ExtJsonResult<AttachVO>();
		try {
			this.view();
			AttachVO vo = (AttachVO) getEntityVO();
			Assert.notNull(vo, "找不到附件信息");
			
			result.setStatus(SUCCESS);
			result.setMessage("成功");
			result.setData(vo);
		} catch(Exception e) {
			String errmsg = "查找附件失败！失败原因：" + e.getMessage();
			log.error(errmsg, e);
			
			result.setStatus(ERROR);
			result.setMessage(errmsg);
		}
		try {
			sendJsonMessage(result);
		} catch (IOException e) {
			log.error(e, e);
		}
		return null;
	}
}
